package com.itbupt.domain.strategy.service.rule.tree.impl;

import com.itbupt.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.itbupt.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import com.itbupt.domain.strategy.repository.IStrategyRepository;
import com.itbupt.domain.strategy.service.armory.IStrategyDispatch;
import com.itbupt.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.itbupt.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author dingchang
 * @Date 2025/3/26 18:57
 * @Description: 库存扣减节点 - 涉及到库存扣减的安全性和一致性
 * 从redis中读取数据做decr扣减操作，而这部分缓存的数据，要放到装配处理里，事先做好数据的装配操作。
 */

@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;
    @Resource
    private IStrategyRepository strategyRepository;


    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-库存扣减 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);

        // 扣减库存
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId, endDateTime);

        if(status) {
            log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);

            // 写入延迟队列， 延迟消费更新数据库记录 - 在trigger里面的job；UpdateAwardStockJob 下消费队列，更新数据库记录
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .strategyId(strategyId)
                    .awardId(awardId)
                    .build());

            // 扣减成功，返回接管 - 由于是库存扣减，所以需要接管 - 然后就是包装消息
            // 注意；根据数据库表中配置走不同的节点。目前数据库配置 ALLOW 是走到下一个节点。
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }

        // 如果库存不足，则直接返回放行
        log.warn("规则过滤-库存扣减-告警，库存不足。userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }

}
